package com.jiadao.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.jiadao.model.AjaxResult;
import com.jiadao.service.DB;
import com.jiadao.service.ProcessService;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.math.NumberUtils;
import org.nutz.dao.entity.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/process")
public class ProcessController{

    @Autowired
    DB db;

    @Autowired
    ProcessService processService;


    @Autowired
    private RepositoryService repositoryService;

    //查询流程列表
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    AjaxResult processList(){
        List<ProcessDefinition> processDefinitions = processService.getProcessList();
        List<Map> mapList = new ArrayList<>();
        if(processDefinitions != null){
            for(ProcessDefinition pd : processDefinitions){
                Map map = new HashMap();
                // pd.getDeploymentId()
                map.put("id", pd.getId());
                map.put("name", pd.getName());
                map.put("key", pd.getKey());
                map.put("desc", pd.getDescription());
                map.put("version", pd.getVersion());
                map.put("deploymentId", pd.getDeploymentId());
                
                mapList.add(map);
            }
        }
        
        AjaxResult result = AjaxResult.success(mapList);
        return result;
    }

    @RequestMapping(value = "/deleteDeploy",method = RequestMethod.GET)
    @ResponseBody
    AjaxResult deleteDeploy(String deploymentId){
       repositoryService.deleteDeployment(deploymentId,true);  //级联删除，如果 boolean值为true时，会删除所有和当前部署的规则相关的信息，包括历史的信息。

        AjaxResult result = AjaxResult.success("ok");
        return result;
    }

    //提交审批动作
    @RequestMapping(value = "/apply/{processKey}/{dataId}",method = RequestMethod.POST)
    @ResponseBody
    AjaxResult apply(@PathVariable("processKey") String processKey,
                    @PathVariable("dataId") String dataId,
                    @RequestBody Map<String,Object> paramsMap){
        //发起人                
        String userId = (String)paramsMap.get("user_id");
        //名称
        String userName =  (String)paramsMap.get("user_name");
        //待办事项名称
        String title = (String)paramsMap.get("instance_title");
        
        
        log.info("dataId====="+dataId);
        log.info("processKey====="+processKey);
        String processInstanceId =  processService.startProcess(processKey,dataId, userId,userName,title,paramsMap);
        log.info("processInstanceId====="+processInstanceId);
        //Map<String, Object> taskVariables = new HashMap<String, Object>();
        //提交表单之后，自动完成第一个节点
        //processService.completeTask(processInstanceId,userId,userName, "0","提交申请",taskVariables);
        return AjaxResult.success("ok",processInstanceId);
    }

    //审批动作
    //result,“0”：初次提交，1：同意,-1：驳回，2:重新提交，3：加签
    //msg:审批语
    @RequestMapping(value = "/approval/{instanceId}",method = RequestMethod.POST)
    @ResponseBody
    AjaxResult approval(@PathVariable("instanceId") String instanceId,
                    @RequestBody(required = false) Map<String,Object> paramsMap){
        String userId = (String)paramsMap.get("user_id");
        String userName =  (String)paramsMap.get("user_name");
        String result = (String)paramsMap.get("result");//审批结果
        String msg = (String)paramsMap.get("msg");//审批语
        processService.completeTask(instanceId, userId,userName,result,msg, paramsMap);
        return AjaxResult.success();
    }

    //审批历史记录
    @RequestMapping(value = "/comment/{instanceId}",method = RequestMethod.GET)
    @ResponseBody
    AjaxResult comment(@PathVariable("instanceId") String instanceId){
        List<Comment> list = processService.getCommentList(instanceId);
        for(Comment com:list){
            System.out.println("ID:"+com.getId());
            System.out.println("Message:"+com.getFullMessage());
            System.out.println("TaskId:"+com.getTaskId());
            System.out.println("Time:"+com.getTime());
            System.out.println("ProcessInstanceId:"+com.getProcessInstanceId());
            System.out.println("UserId:"+com.getUserId());
        }
        return AjaxResult.success(list);
    }


    //待办事项列表
    @RequestMapping(value = "/taskList/{userId}",method = RequestMethod.POST)
    @ResponseBody
    AjaxResult taskList(
                    @PathVariable("userId") String userId,
                    //@RequestParam(value="pageIndex",defaultValue = "1") int pageIndex,
                    //@RequestParam(value="pageSize",defaultValue = "20") int pageSize
                    @RequestBody(required = false) Map<String,String> conditionMap
                    ){
        if(conditionMap==null){
            conditionMap = new HashMap<>();
        }
        int pageIndex = NumberUtils.toInt(conditionMap.get("pageIndex"), 1);
        int pageSize = NumberUtils.toInt(conditionMap.get("pageSize"), 20);
        AjaxResult result = processService.queryTaskList(userId,  pageIndex, pageSize);
        List<Record> taskList = (List<Record>)result.get("data");
        // if(taskList!=null){
        //     for(Record task:taskList){
        //         //instance_id  task_name,data_id,process_name
        //         System.out.println("task id :"+task.getString("task_id"));
        //         System.out.println("task instance_id :"+task.getString("instance_id"));
        //         //当前任务名称
        //         System.out.println("task task_name :"+task.getString("task_name"));
        //         System.out.println("task process_name :"+task.getString("process_name"));
        //         System.out.println("task leave id :"+task.getString("data_id"));
        //     }
        // }
        
        return result;
        
    }

    //待办事项列表
    @RequestMapping(value = "/doneTaskList/{userId}",method = RequestMethod.POST)
    @ResponseBody
    AjaxResult doneTaskList(
                    @PathVariable("userId") String userId,
                    //@RequestParam(value="pageIndex",defaultValue = "1") int pageIndex,
                    //@RequestParam(value="pageSize",defaultValue = "20") int pageSize
                    @RequestBody(required = false) Map<String,String> conditionMap
                    ){
        
        if(conditionMap==null){
            conditionMap = new HashMap<>();
        }
        int pageIndex = NumberUtils.toInt(conditionMap.get("pageIndex"), 1);
        int pageSize = NumberUtils.toInt(conditionMap.get("pageSize"), 20);
        AjaxResult result = processService.queryDoneTaskList(userId, pageIndex, pageSize);
        List<Record> taskList = (List<Record>)result.get("data");
        // if(taskList!=null){
        //     for(Record task:taskList){
        //         //instance_id  task_name,data_id,process_name
        //         System.out.println("task id :"+task.getString("task_id"));
        //         System.out.println("task instance_id :"+task.getString("instance_id"));
        //         //当前任务名称
        //         System.out.println("task task_name :"+task.getString("task_name"));
        //         System.out.println("task process_name :"+task.getString("process_name"));
        //         System.out.println("task leave id :"+task.getString("data_id"));
        //     }
        // }
        
        return result;
        
    }

    @RequestMapping(value = "/getProcessImage/{processKey}",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public BufferedImage getImage(@PathVariable("processKey") String processKey) throws IOException {
        InputStream inputStream = processService.getDefinitionImage(processKey);
        return ImageIO.read(inputStream);
    }


    @RequestMapping(value = "/getInstanceImage/{instanceId}",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public BufferedImage getImageByInstanceId(@PathVariable("instanceId") String instanceId) throws IOException {
        InputStream inputStream = processService.getResourceDiagramInputStream(instanceId);
        return ImageIO.read(inputStream);
    }



}